package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class DirectListener {
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(queues ="hmall.insert" )
    public void handleMessage(String msg) throws IOException {
        System.out.println("---------------"+msg);
        Item item = JSON.parseObject(msg, Item.class);
        ItemDoc itemDoc = new ItemDoc();
        BeanUtils.copyProperties(item,itemDoc);
        String json = JSON.toJSONString(itemDoc);
        IndexRequest indexRequest = new IndexRequest("hm-mall")
                .id(itemDoc.getId().toString())
                .source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("-------------------------------------");
        System.out.println("已新增‘"+itemDoc.getId()+"’号商品");
        System.out.println("-------------------------------------");
    }
    @RabbitListener(queues = "hmall.delete")
    public void handleDeleteMessage(Long id) throws IOException {
        System.out.println("====================="+id);
        DeleteRequest deleteRequest = new DeleteRequest("hm-mall").id(id.toString());
        client.delete(deleteRequest,RequestOptions.DEFAULT);
        System.out.println("-------------------------------------");
        System.out.println("已删除‘"+id+"’号商品");
        System.out.println("-------------------------------------");

    }
}
